import * as THREE from 'three';
import eventBus from "@/js/eventBus";

import scaleBox from './scaleBox';
let raycaster = '';
var tween = '';
class threeEvent {
	
	
	constructor() {
		this.dragStatus = false;
		this.pageXY = {
			x:0,
			y:0
		}
		this.controls = ''
		this.camera = ''
		this.scene = ''
	}
	init(sceneMrg) {
		this.camera = sceneMrg.camera;
		this.scene = sceneMrg.scene;
		this.controls = sceneMrg.controls;
		let self = this;
		let renderer = sceneMrg.renderer
		this.renderer = renderer
		document.addEventListener('click', self.onClick.bind(self), false);
		document.addEventListener('dblclick', self.domclick.bind(self), false);
		renderer.domElement.addEventListener(
			'contextmenu',
			self.contextmenu.bind(self),
			false
		);
		document.addEventListener(
			'mousemove',
			self.mousemove.bind(self),
			false
		);
		renderer.domElement.addEventListener(
			'mousedown',
			self.mousedown.bind(self),
			false
		);

		renderer.domElement.addEventListener(
			'click',
			self.mouseclick.bind(self),
			false
		);
	}

	mouseclick(event) {}

	eventFind(event) {
		let camera = this.camera;
		var mouse = new THREE.Vector2();
		mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

		const rect = this.renderer.domElement.getBoundingClientRect();
		mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
		mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;


		//mouse.unproject(camera);
		// 通过射线投射来检测是否点击到几何体
		raycaster = new THREE.Raycaster();

		raycaster.setFromCamera(mouse, camera);
		var intersects = raycaster.intersectObjects(this.scene.children, true);
		// 判断是否有交叉物体
		if (intersects.length > 0) {
			//console.log("Clicked on cube!", intersects[0].object.userData.layer, intersects[0].position);
			let item = intersects[0].object.userData;
			//console.log("----------------点击机柜----------------:", item, intersects[0].object)
			const point = intersects[0].point;
			
			return {
				object: intersects[0].object,
				intersects: intersects[0],
				data: intersects[0].object.userData,
			};
		}

		return null;
	}

	mousedown(e) {
		console.log('我点击了e.page:', e);
		this.pageXY.x = e.pageX;
		this.pageXY.y = e.pageY;

		this.dragStatus = false;

		// let item = this.eventFind(e)
		// this.camera.position.copy(item.intersects.point);
	}

	mousemove(event) {
		//let item = this.eventFind(event);
	  return 
		this.dragStatus = true;
    try{
			if(item.object.modeldata){
				console.log("移动了鼠标", item.object.modeldata, item)
				scaleBox.setScale(item.object)
			}
		}catch(e){}
		
		
	}

	contextmenu(event) {
		event.preventDefault();

		if (this.dragStatus) {
			this.dragStatus = false;
			return;
		}
		let item = this.eventFind(event);
		item.intersects.point.y = item.intersects.point.y * 1000;
		item.intersects.point.x = item.intersects.point.x * 1000;
		console.log(
			'右键处理:',
			item,
			item.object.parent,
			item.intersects.point,
			item.object.userData.vertices[0]
		);

		//let parentNode = item.object.parent
		try {
			//parentNode.remove(item.object)
			let list = [
				{
					title: '删除',
					type: 'delete',
				},
				{
					title: '增加设备',
					type: 'add',
				},
			];
			item['list'] = list;
			item['event'] = event;
			eventBus.emit('contextmenuBnt', item);
		} catch (e) {
			console.log('移出模型错误:', e);
		}

		// console.log("item:", item)

		// if(item)

		// eventBus.emit('select-cabinet', item)
	}

	onClick (event) {
		let item = this.eventFind(event);
		if(item){
			if(item.object.modeldata){
				
				// scaleBox.setScale(item.object)
				/*if(item.object.face.materialIndex === 4){
					console.log("单机设备2：", item.object.modeldata, item)
				}
				*/
			}
		}
	}

	onClick_(event) {
		console.log('---click---');

		let item = this.eventFind(event);
		let self = this;
		var distance = item.object.position.distanceTo(this.camera.position);
		var targetPosition = new THREE.Vector3().copy(item.object.position);
		var cameraPosition = new THREE.Vector3().copy(this.camera.position);
		var newCameraPosition = targetPosition
			.clone()
			.sub(raycaster.ray.direction.multiplyScalar(distance));

		if (tween) tween.stop();
		tween = new TWEEN.Tween(cameraPosition)
			.to(newCameraPosition, 1000) // 过渡时间为500毫秒
			.onUpdate(function () {
				// 更新相机位置和朝向
				self.camera.position.copy(item.object.position);
				self.camera.lookAt(item.object.position);
			})
			.start();
	}

	lookCenter(mesh) {
		this.camera.lookAt(mesh.position);

		var meshPosition = mesh.position.clone(); // 克隆 Mesh 的位置

		// 将 Mesh 的位置转换为相机坐标系中的位置
		meshPosition.project(this.camera);

		// 计算需要将 Mesh 移动到视图中央的向量
		var moveVector = new THREE.Vector3(0, 0, -meshPosition.z);

		// 将 Mesh 移动到视图中央
		mesh.position.add(moveVector);

		return;
		// 获取场景中 Mesh 的包围盒
		var boundingBox = new THREE.Box3().setFromObject(mesh);

		// 计算 Mesh 中心点的世界坐标
		var center = new THREE.Vector3();
		boundingBox.getCenter(center);
		center.applyMatrix4(mesh.matrixWorld);

		// 计算相机到 Mesh 中心点的向量
		var direction = new THREE.Vector3().subVectors(
			center,
			this.camera.position
		);

		// 将 Mesh 移动到视图中心
		this.camera.position.add(direction);

		// 更新相机的投影矩阵
		this.camera.updateProjectionMatrix();
	}

	lookFor(mesh) {
		//return
		// 目标距离（悬停距离）
		var hoverDistance = 500;

		// 计算相机与 Mesh 的当前距离
		var distance = this.camera.position.distanceTo(mesh.position);

		if (distance > hoverDistance) {
			// 如果当前距离大于悬停距离，则将相机向前移动以接近 Mesh
			var moveDistance = distance - hoverDistance;
			var direction = new THREE.Vector3()
				.subVectors(mesh.position, this.camera.position)
				.normalize();
			this.camera.position.addScaledVector(direction, moveDistance);

			// 更新相机的投影矩阵
			this.camera.updateProjectionMatrix();
		}
	}

	domclick(event) {
		let item = this.eventFind(event);
    if(item){
			if(item.object.modeldata){
				console.log("双击设备：", item.object.modeldata, item)
				eventBus.emit("areadata",item.object.modeldata)
				scaleBox.setScale(item.object)
			}
		}
		
		

	
    
		
	}
}

export default new threeEvent();
